package com.example.searchjavaapi.api;

import com.example.searchjavaapi.common.AjaxResult;
import com.example.searchjavaapi.searcher.Result;

import com.example.searchjavaapi.searcher.Searcher;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/search")
public class Search {

    @Autowired
    private Searcher searcher;
    private Gson gson = new GsonBuilder().create();

    public Search() throws IOException {

    }



//    public void search(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//
//        resp.setContentType("application/json;charset=utf-8");
//        String query = req.getParameter("query");
//        if (query==null||query.equals("")){
//            resp.setStatus(404);
//            resp.getWriter().write("query参数非法");
//            return;
//        }
//        List<Result> results = searcher.search(query);
//        String respString = gson.toJson(results);
//        resp.getWriter().write(respString);
//
//    }

    @RequestMapping("search1")
    public AjaxResult search1(String query,Integer pindex,Integer psize){
        if (query==null||query.equals("")){
            return AjaxResult.fail(-1,"query参数非法",null);
        }
        if (pindex<=0 || psize<=0){
            return AjaxResult.fail(-1,"页码错误",null);
        }

        //第几条开始
        int offset = (pindex-1)*psize;
        //获取到第几条
        int endset = offset+psize-1;
        //查询结果
        List<Result> list = searcher.search(query);
        if (list == null){
            return AjaxResult.success(10,"没有找到您要查询的数据",null);
        }
        //实现分页查询
        //只将指定范围的数据返回
        ArrayList<Result> list1 = new ArrayList<>();
        for(int i = offset;i<=endset;i++){
            list1.add(list.get(i));
        }

        HashMap<String, Object> hash = new HashMap<>();
        int items = list.size();
        System.out.println(items);
        double pcount1 = items/psize*1.0;
        int pcount = (int)Math.ceil(pcount1);
        hash.put("list",list1);
        hash.put("pcount", pcount);
        return AjaxResult.success(hash);

    }




}
